﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using System.Configuration; 
using Spring.Data.Common;
using System.IO;

namespace Vision.Utilities.CMS6UpdateTool
{
    [ConfigurationElementType(typeof(AutoUpdateDatabaseProcessorConfigurationElement))]
    public class DatabaseUpdateProcessor : IUpdateProcessor
    {
        public DatabaseUpdateProcessor(string packageFolder, IEnumerable<string> files, int order = 0) 
        {
            PackageFolder = packageFolder;
            Files = files;
            Order = order;
        }

        public int Order { get; private set; }
        public string PackageFolder { get; private set; }
        public IEnumerable<string> Files { get; private set; }

        public void Process(UpdateProcessorContext context)
        {
            var databaseExtractedPath = FileSystemUtility.Combine(context.ExtractedPackagePath, PackageFolder);
            if (Files.Any() && Directory.Exists(databaseExtractedPath))
            {
                var adoTemplate = AdoUtility.GetAdoOperations(context.ItemUpdateContext.Args.DBConnectionString);
                foreach (var file in Files)
                {
                    var sqlFile = FileSystemUtility.Combine(databaseExtractedPath, file);
                    adoTemplate.ExecuteNonQueryFromFile(sqlFile);
                }
            }
        }
    }
}